<template>
    <section>
        <header>
            <div class="header-left">
                <el-upload
                    v-loading="uploadLoading"
                    style="display:inline-block;"
                    action="string"
                    :show-file-list="false"
                    :before-upload="onBeforeUploadImage"
                    :http-request="(param)=>UploadImage(param)"
                >
                    <img v-show="userPic" :src="userPic" class="avatar">
                    <span class="iconfont icon-camera"></span>
                </el-upload>

                <div :class="['user-message',(!baseLabelList || !baseLabelList.length) ? 'center-show':'']">
                    
                    <h4>
                        <el-tag v-if="user.isDelete == 1" class="del-tag" type="danger" effect="dark">{{$t('common.base.deleted')}}</el-tag>
                        <span class="user-top">
                            <template v-if="isOpenData && user.staffId">
                                <open-data :openid="user.staffId"></open-data>
                            </template>

                            <template v-else>
                                {{user.displayName}}
                            </template>
                        </span>

                        <template v-if="user.state">
                            <i class="circle" :style="{backgroundColor:userStateColor}"></i>
                            <span class="work-state">{{getUserWorkStateLabel(stateText)}}</span>
                        </template>
                    </h4>

                    <div class="tags" v-if="baseLabelList && baseLabelList.length">
                        <template v-for="(tag,index) in baseLabelList">
                            <!-- 最多展示4个 -->
                            <el-tag :key="tag.id" v-if="index < 4">{{tag.tagName}}</el-tag>
                        </template>
                        <template  v-if="baseLabelList.length > 4">
                            <el-popover
                                placement="bottom"
                                width="320"
                                v-model="tagVisible"
                                popper-class="more-tag">
                                <template v-for="tag in baseLabelList">
                                    <el-tag :key="tag.id">{{tag.tagName}}</el-tag>
                                </template>
                                
                                <i 
                                    :class="['iconfont','icon-more',tagVisible ? 'more-rotate' :'']" 
                                    slot="reference" 
                                ></i>
                            </el-popover>
                        </template>
                    </div>
                </div>
            </div>

            <!-- // 是否可以删除账号      canDeleteAccount
            // 是否可以停用账号      canStopAccount
            // 是否可以修改账号      canUpdateAccount -->
            <div class="header-right" v-if="Object.keys(showButton).length">
                
                <template v-if="user.isDelete != 1">
                    <!-- 修改密码按钮展示规则：有修改密码的权限&&非企微端&非钉钉端 -->
                    <el-button 
                        v-if="showButton.canUpdatePasswd" 
                        type="plain-third" 
                        @click="updatePwdBtnHandle"
                    >
                        <i class="iconfont icon-suo"></i>
                        
                        <b>{{ $t('common.button.changePwd') }}</b>
                    </el-button>

                    <el-button
                        v-if="showButton.canUpdateAccount"
                        type="plain-third" 
                        @click="editBtnHandle"
                    >
                        <i class="iconfont icon-edit-square1"></i>
                        
                        <b>{{ $t('common.base.edit') }}</b>
                    </el-button>

                    <el-button 
                        :type="user.enabled ? 'danger' : 'primary'" 
                        @click="enabledBtnHandle"
                        v-if="showButton.canStopAccount"
                    >
                        <!-- <i class="iconfont icon-close1"></i> -->
                        <b>{{user.enabled ? $t('common.base.deactivate') : $t('common.base.enable')}}</b>
                    </el-button>

                    <!-- 钉钉端和企微端没有删除和修改密码的权限 -->
                    <el-button 
                        type="danger" 
                        @click="delBtnHandle"
                        v-if="showButton.canDeleteAccount"
                    >
                        <!-- <i class="iconfont icon-delete"></i> -->
                        <b>{{ $t('common.base.delete') }}</b>
                    </el-button>
                </template>

                <!-- 已删除账号后的权限按钮 -->
                <template v-else>
                    <el-button 
                        v-if="showButton.canRecover"
                        type="plain-third" 
                        @click="resume"
                    >
                        <b>{{ $t('common.button.recover') }}</b>
                    </el-button>

                    <el-button 
                        v-if="showButton.canTransfer"
                        type="plain-third" 
                        @click="createTransTab"
                    >
                        <b>{{ $t('common.button.toHandOver') }}</b>
                    </el-button>
                </template>
            </div>
        </header>

        <update-pwd ref="updatePwdRef"></update-pwd>
        <!-- 编辑信息弹框 -->
        <UpdateMessage 
            v-if="updateMessageVisible"
            v-model="updateMessageVisible" 
            :user="user" 
            :userRow="userRow"
            :account-info="internalAccountInfo"
            @update="updateMes">
        </UpdateMessage>
    </section>
</template>

<script>
import * as UserCenterApi from '@src/api/UserCenterApi';
// 默认用户头像
import { getOssUrl } from '@src/util/assets'
const defaultAvatar = getOssUrl('/avatar.png')

import { isOpenData, openAccurateTab } from '@src/util/platform';

// 修改密码组件
import UpdatePwd from './UpdatePwd';

// 修改账户组件
import UpdateMessage from './UpdateMessage';


/* util */
import Uploader from 'packages/BaseUpload/uploader';

import { getRootWindow } from '@src/util/dom';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { UserWorkStateLabelEnum } from '@model/enum/LabelEnum'

import { t } from '@src/locales'

let win = getRootWindow(window);
let origin = window.location.origin;

export default {
    name:'UserHeader',

    data(){
        return {
            internalAccountInfo: {}, //国际化账号信息
            // 修改账户弹框展示/隐藏
            updateMessageVisible:false,
            // 工作状态数据对象
            userStateMap: {},
            // 工作状态名字
            stateText:'',
            // 标签列表
            baseLabelList:[],

            userRow:{},
            tagVisible:false,

            // 用户头像
            userPic:'',

            uploadLoading:false,
            // 获取登陆的userId，匹配与当前页面的用户是否是同一个人
            loginUserId:localStorage.getItem('userId')
        }
    },

    props:{
        user:{
            type:Object,
            required:true
        },

        // 权限按钮
        showButton:{
            type:Object,
            required:true
        },

        userId:{
            type:String,
            required:true
        },
    },

    inject:['initData'],

    computed:{
        userStateColor(){
            return this.userStateMap[this.stateText]
        }
    },

    watch:{
        // 用户工作状态名称
        'user.state':{
            immediate:true, 
            handler(newValue,oldValue){
                this.stateText = newValue;
            }
        },

        // 用户头像
        'user.head':{
            // immediate:true,
            handler(newValue,oldValue){
                this.userPic = newValue || defaultAvatar;
            }
        },

        // 用户名称
        // 'user.displayName':{
        //     // immediate:true,
        //     handler(newValue,oldValue){
                
        //     }
        // }
    },

    components:{
        UpdatePwd,
        UpdateMessage,
    },

    mounted(){
        this.getWorkState();
        this.getBaseLabelData();
        // 当前登陆的用户与当前页面是同一个人，需要监听右上角的修改状态
        if(this.loginUserId === this.userId){
             // 当框架右上角修改了工作状态，这边也需要更新
            window.addEventListener('message', event=>{
                const { state } = event.data || {};
                if(state){
                    this.stateText = state;
                }
            });
        }
       
    },

    methods:{
        // 获取用户工作状态多语言label
        getUserWorkStateLabel(name) {
            return UserWorkStateLabelEnum[name] || name
        },
        // 获取工作状态列表
        getWorkState(){
            this.$http.get('/setting/getStateColorMap').then(res=>{
                this.userStateMap = res || {}
            })
        },

        // 获取标签列表
        getBaseLabelData(){
            this.$http.get('/security/user/getUserLabels',{userId:this.userId}).then(res=>{
                const { errorCode, data } = res;
                if(errorCode !== 0) return;
                this.baseLabelList = data || []
            })
        },

        // 启用/停用
        enabledBtnHandle(){
            this.$http
                .post('/security/user/enable', { userId: this.user.userId }, false)
                .then(res => {
                    if (res.status) return this.$platform.alert(res.message);
                    this.$emit("getUserInfo")
                })
                .catch(err => {
                    console.error('toggleStatus catch err', err);
                });
        },

        // 删除
        async delBtnHandle(){
            if (await this.$platform.confirm(t('personal.delStatffTip'))) {
                this.$http
                .post('/security/user/delete', { userId: this.user.userId },false)
                .then(res => {
                    if (res.status) return this.$platform.alert(res.message);
                    this.$emit("getUserInfo")
                })
                .catch(err => {
                    console.error('toggleStatus catch err', err);
                });
            }
        },

        updateMes(){
            this.$emit('getUserInfo');
            this.getBaseLabelData()
        },

        // 展示修改密码弹框
        updatePwdBtnHandle(){
            if (!this.showButton.canUpdatePasswd) {
                console.warn('没有修改密码权限或者配置');
                return;
            }
            this.$refs.updatePwdRef.openDialog();
        },

        async editBtnHandle(){
            this.userRow = {
                ...this.user,
                labelList:this.baseLabelList
            }
            try {
                await this.getInternalAccountInfo({ userId: this.user.userId })
            } catch (error) {
                console.log(error)
            }
            this.updateMessageVisible = true
        },
        async getInternalAccountInfo(params) {
            try {
                const { status, data= {} } = await UserCenterApi.getInternalAccountInfo(params)
                if(status == 0) {
                   this.internalAccountInfo = data || {}
                }
            } catch (error) {
                console.warn('getInternalAccountInfo error', error)
            }
        },
        onBeforeUploadImage (file) {
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;
            
            if (!isJPG) {
                this.$message.error(t('common.validate.imageType'));
            }
            if (!isLt2M) {
                this.$message.error(t('common.validate.imageLimit', { limit: '2mb' }));
            }
            
            return isJPG && isLt2M;
        },

        UploadImage(param){
            this.uploadLoading = true;
            Uploader.upload(param.file, '/files/upload').then((result) => {
                if (result.status != 0) {
                    this.$message({
                        message: `${result.message}`,
                        duration: 1500,
                        type: 'error',
                    });
                    return;
                }
                
                let file = result.data;
                let item = {
                    id: file.id,
                    filename: file.fileName,
                    // 如果后端返回url,必须使用。如果后端不返回，需要拼接
                    url: file.ossUrl || file.url || `/files/get?fileId=${file.id}`,
                    fileSize: file.fileSizeStr,
                };
                this.saveImage( item.url);
            }).catch((err) => {
                console.warn(err)
                this.uploadLoading = false;
            }).finally(() => {  })
        },

        // 保存头像
        saveImage(url){
            this.$http
                .post('/dd/user/headImage', { 
                    userId: this.userId,
                    url
                }, false)
                .then(res => {
                    if (res.status) return this.$platform.alert(res.message);

                    this.userPic = url;

                    this.uploadLoading = false;
                    
                    // 当前登陆的用户与当前页面是同一个人，需要更新右上角的用户头像
                    if(this.loginUserId === this.userId){
                        win.postMessage({ userPic:this.userPic }, origin);
                    }
                })
                .catch(err => {
                    console.error('toggleStatus catch err', err);
                    this.uploadLoading = false
                });
        },

        async resume() {
            try {
                if (await this.$platform.confirm(t('common.base.tip.recoverAccountConfirm'))) {
                    const { status, message } = await this.$http.post('/security/user/resume',
                        { userId: this.userId},
                        false
                    );
                    
                    let isSucc = status == 0;
                    this.$platform.notification({
                        title: isSucc ? t('common.base.success') : t('common.base.fail'),
                        message: isSucc ? t('common.base.tip.recoverAccountSuccess') : message,
                        type: isSucc ? 'success' : 'error'
                    });

                    this.$emit("getUserInfo")
                }
            } catch (error) {
                console.error(error);
            }
        },

        // 去转交
        createTransTab() {
            let fromId = window.frameElement.getAttribute('id');
            // this.$platform.openTab({
            //     id: 'M_JOBTRANSFER_DETAIL',
            //     title: '转交详情',
            //     close: true,
            //     url: `/jobtransfer/view?type=event&userId=${this.userId}`,
            //     fromId
            // });
            openAccurateTab({
                type: PageRoutesTypeEnum.PageJobtransferView,
                params: `type=event&userId=${this.userId}`,
                fromId
            })
        },
    }
}
</script>


<style lang="scss" scoped>
header{
    display:flex;
    width:100%;
    height:88px;
    background:#fff;
    padding:16px;
    border-radius: 4px;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    position: relative;
    overflow: hidden;

    &::before,&::after{
        display: block;
        content:'';
        width: 105px;
        height: 43px;
        background: #C3E2FF;
        filter: blur(38px);
        position: absolute;
    }
    &::before{
        top:0;
        left:0px;
    }
    &::after{
        right:0;
        bottom:0px;
        width: 76px;
        height: 63px;
        background: #D1FBFF;
    }
    .header-left{
        display: flex;
        width:670px;
        
        .user-message{
            padding-left:12px;
            .del-tag{
               border-color:#ff4d4f;
               background:#ff4d4f;
               border-radius: 12px;
               padding:0 8px;
               margin-right:12px;
               line-height:22px;
               font-weight: 700;
            }
            h4{
                height: 22px;
                font-size: 16px;
                font-weight: 600;
                color: #333333;
                line-height: 22px;
                margin:2px 12px 8px 0;
                display: flex;
                align-items: center;
                .user-top{
                    max-width:450px;
                    height: 22px;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    overflow: hidden;
                }
            }
            .circle{
                margin:0 7px 0 12px;
                display: block;
                width:8px;
                height:8px;
                border-radius: 50%;
            }
            .work-state{
                font-size: 14px;
                font-weight: 400;
                color: #595959;
                line-height: 22px;
                
            }

            .tags{
                display: flex;
                flex-wrap: wrap;
                .iconfont{
                    cursor:pointer;
                }
                .icon-more{
                    display: block;
                    color:#8C8C8C;
                    transition: all 0.4s;
                }
                .more-rotate{
                    transform:rotate(180deg)
                }
                .el-tag--small{
                    margin: 0 8px 0px 0;
                }
                .button-new-tag{
                    line-height: 22px;
                    padding: 0;
                    color: #8C8C8C;
                    font-size: 14px;
                    cursor: pointer;
                    display: flex;
                    align-content: center;
                }
            }
        }

        .center-show{

            display: flex;
            align-items: center;
        }

        .el-upload{
            height:56px;
        }
    }
    .header-right{
        height:56px;
        padding:12px 0;
        position: relative;
        z-index:9;
        width:400px;
        display: flex;
        justify-content: flex-end;
        button.el-button{
            .iconfont{
                margin-right:4px;
                font-size:16px;
            }
            ::v-deep span{
                display: flex;
                align-items: center;
            }
            b{
                font-weight: normal;
            }
        }
    }
}
::v-deep .el-upload{
    position: relative;
    width: 56px;
    height: 56px;
    border-radius: 8px;
    overflow: hidden;
    img{
        width: 56px;
        height: 56px;
        object-fit: cover;
    }
    .iconfont{
        position: absolute;
        width:56px;
        height:56px;
        top:0;
        left:0;
        background: rgba(0, 0, 0, 0.5);
        opacity: 0;
        color:#fff;
        line-height: 56px;
        transition: opacity .5s;
    }
    .icon-camera{
        font-size:20px;
    }
    &:hover{
        .iconfont{
            opacity: 1;
        }
    }
}
.tag-tips{
    color: #BFBFBF;
    font-size: 14px;
}

.header-right{
    .el-button--danger{
        &:focus,&:hover{
            background: #f78989;
            border-color: #f78989;
            color:#fff;
        }
    }
}
</style>

<style lang="scss">
.more-tag{
    .el-tag{
        margin:0 8px 8px 0;
    }
}
</style>